<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\App\Utils\Logger\Handler;

use Monolog\Handler\RotatingFileHandler;
use Monolog\Logger;

class RotatingFileFilterHandler extends RotatingFileHandler
{
    /**
     * Minimum level for logs that are passed to handler.
     *
     * @var int[]
     * @phpstan-var Level[]
     */
    protected $acceptedLevels;

    /**
     * @param array|int|string $level
     */
    public function __construct(string $filename, int $maxFiles = 0, $level = Logger::DEBUG, bool $bubble = true, ?int $filePermission = null, bool $useLocking = false)
    {
        $this->setAcceptedLevels($level);
        if (is_array($level)) {
            $level = min($level);
        }
        parent::__construct($filename, $maxFiles, $level, $bubble, $filePermission, $useLocking);
    }

    /**
     * @param array|int|string $level
     */
    public function setAcceptedLevels($level = Logger::DEBUG): self
    {
        if (! is_array($level)) {
            $level = [$level];
        }

        $acceptedLevels = array_map('Monolog\Logger::toMonologLevel', $level);
        $this->acceptedLevels = array_flip($acceptedLevels);

        return $this;
    }

    /**
     * {@inheritDoc}
     */
    public function isHandling(array $record): bool
    {
        return isset($this->acceptedLevels[$record['level']]);
    }
}
